package com.qian.service.ddj.serviceImpl;

import com.qian.api.ddj.model.LoginLog;
import com.qian.api.ddj.service.ILoginLogService;
import com.qian.service.ddj.dao.LoginLogRepository;
import com.qian.service.ddj.entity.DdjLoginLog;
import com.qian.service.ddj.entity.DdjUser;
import com.yaowk.service.common.BaseRepository;
import com.yaowk.service.common.BaseServiceImpl;
import com.yaowk.service.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class LoginLogServiceImpl extends BaseServiceImpl<LoginLog, DdjLoginLog, Long> implements ILoginLogService {
    @Autowired
    private LoginLogRepository dao;

    @Override
    protected BaseRepository getDao() {
        return dao;
    }

    @Override
    protected DdjLoginLog model2Entity(LoginLog model) {
        DdjLoginLog ddjLoginLog = null;
        if (isNotEmpty(model)) {
            ddjLoginLog = new DdjLoginLog();
            ddjLoginLog.setId(model.getId());
            ddjLoginLog.setCreateTime(model.getCreateTime());
            ddjLoginLog.setIp(model.getIp());
            SysUser user = new SysUser();
            user.setId(model.getUserId());
            ddjLoginLog.setUser(user);
        }
        return ddjLoginLog;
    }

    @Override
    protected LoginLog entity2model(DdjLoginLog entity) {
        LoginLog loginLog = null;
        if (isNotEmpty(entity)) {
            loginLog = new LoginLog();
            loginLog.setId(entity.getId());
            loginLog.setCreateTime(entity.getCreateTime());
            loginLog.setIp(entity.getIp());
            loginLog.setUsername(entity.getUser().getUsername());
            loginLog.setUserId(entity.getUser().getId());
        }
        return loginLog;
    }

    @Override
    public LoginLog findLastOneByUserId(Integer userId) {
        PageRequest pageRequest = new PageRequest(0, 2, new Sort(Sort.Direction.DESC, "createTime"));
        DdjLoginLog ddjLoginLog = new DdjLoginLog();
        DdjUser ddjUser = new DdjUser();
        ddjUser.setId(userId);
        ddjLoginLog.setUser(ddjUser);
        Page<DdjLoginLog> page = dao.findAll(Example.of(ddjLoginLog), pageRequest);
        ddjLoginLog = null;
        if (page.getContent().size() == 2) {
            ddjLoginLog = page.getContent().get(1);
        }
        return entity2model(ddjLoginLog);
    }
}
